/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.mybatis.interceptor;

import com.iwindplus.boot.mybatis.domain.property.MybatisProperty.FieldConfig.CryptoConfig;
import com.iwindplus.boot.mybatis.manager.MybatisFieldManager;
import jakarta.annotation.Resource;
import java.sql.Statement;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

/**
 * MyBatis 出参拦截器（解密/脱敏）
 *
 * @author zengdegui
 * @since 2025/04/22 00:46
 */
@Slf4j
@Intercepts(@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class))
public class MybatisOutputInterceptor implements Interceptor {

    @Resource
    private MybatisFieldManager mybatisFieldManager;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object data = invocation.proceed();
        final CryptoConfig crypto = this.mybatisFieldManager.getMybatisProperty().getField().getCrypto();
        if (!crypto.getEnabled()) {
            return data;
        }

        if (!crypto.getOutputDecrypt()) {
            return data;
        }

        this.mybatisFieldManager.processHandler(data, false, false, crypto.getOutputDecrypt());

        return data;
    }
}
